#import "PostViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"
#import "UserManager.h"
#import "RegexKitLite.h"
#import "RegisterViewController.h"
#import "LoginViewController.h"
#import "BaseHiddenTabBarController.h"
#import "MenuViewController.h"
#import "NetWorkManager.h"
#import "CMActionSheet.h"

#define IMAGE_FILE_PATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

@implementation PostViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc {
    PP_RELEASE(hudLoading);
    PP_RELEASE(postView);
    PP_RELEASE(postBtn);
    PP_RELEASE(showCameraAndPohto);
    PP_RELEASE(inputFullLine);
    PP_RELEASE(previewImage);
    PP_RELEASE(photoView);
    PP_RELEASE(deleteMark);
    PP_RELEASE(cameraPhotoView);
    PP_RELEASE(actionView);
    PP_RELEASE(postBgView);
    PP_RELEASE(realImg);
    PP_RELEASE(rabbitBtn);
    PP_RELEASE(browserPhotos);
    PP_RELEASE(scanBtn);
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.viewDeckController.panningMode = IIViewDeckNoPanning;
    self.viewDeckController.centerhiddenInteractivity = IIViewDeckCenterHiddenNotUserInteractiveWithTapToClose;
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor]; //导航上那条黑线的原因在这里
    baseTitle.text = @"发表";

    self.viewDeckController.delegate = self;

//    //点击其他区域隐藏键盘
//    UITapGestureRecognizer *tapGuesure = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewTap:)];
//    tapGuesure.cancelsTouchesInView = NO;
//    [self.view addGestureRecognizer:tapGuesure];
//    [tapGuesure release];

    UIButton* menuBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_menu_1.png"] forState:UIControlStateNormal];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_menu_2.png"] forState:UIControlStateHighlighted];
    [menuBtn addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *menuBarBtn = [[[UIBarButtonItem alloc] initWithCustomView:menuBtn] autorelease];
    [self.navigationItem setLeftBarButtonItem:menuBarBtn];
    
    postBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [postBtn setBackgroundImage:[UIImage imageNamed:@"post_joke_1.png"] forState:UIControlStateNormal];
    [postBtn setBackgroundImage:[UIImage imageNamed:@"post_joke_2.png"] forState:UIControlStateHighlighted];
    postBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [postBtn addTarget:self action:@selector(post:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* postBarBtn= [[[UIBarButtonItem alloc] initWithCustomView:postBtn] autorelease];
    [self.navigationItem setRightBarButtonItem:postBarBtn];
    
//    UIImage *inpugBackGround = [[UIImage imageNamed:@"post_input.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    UIImage *inputFullLineBackgournd = [[UIImage imageNamed:@"post_full_line.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];
    inputFullLine.image = inputFullLineBackgournd;
    
    UIImage *preViewFrameImg = [[UIImage imageNamed:@"preview_frame.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:10];
    previewImage.image = preViewFrameImg;

    postView.returnKeyType = UIReturnKeyDefault;
    postView.delegate = self;
    postView.placeholder = @"输入你要发布的内容...";

    [self registerForKeyboardNotifications];
    [postView becomeFirstResponder];
    browserPhotos = [[NSMutableArray alloc] init];

}

- (void) registerForKeyboardNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    CGFloat distanceToMove = keyboardSize.height;
 
    CGRect postViewFrame = CGRectMake(postBgView.frame.origin.x, postBgView.frame.origin.y, postBgView.frame.size.width,self.view.frame.size.height - distanceToMove);
    postBgView.frame = postViewFrame;
    [showCameraAndPohto addTarget:self action:@selector(camera:) forControlEvents:UIControlEventTouchDown];
}

- (void) keyboardWillHide:(NSNotification *)notification {
    CGRect postViewFrame = CGRectMake(postBgView.frame.origin.x, postBgView.frame.origin.y, postBgView.frame.size.width,self.view.frame.size.height - 216);
    postBgView.frame = postViewFrame;
}

////点击其他区域隐藏键盘
//-(void)viewTap:(UITapGestureRecognizer *)tapGuesture
//{
//    [postView resignFirstResponder];
//}

- (void)viewDidUnload
{
    PP_RELEASE(hudLoading);
    PP_RELEASE(postView);
    PP_RELEASE(postBtn);
    PP_RELEASE(showCameraAndPohto);
    PP_RELEASE(inputFullLine);
    PP_RELEASE(previewImage);
    PP_RELEASE(photoView);
    PP_RELEASE(deleteMark);
    PP_RELEASE(cameraPhotoView);
    PP_RELEASE(actionView);
    PP_RELEASE(postBgView);
    PP_RELEASE(realImg);
    PP_RELEASE(rabbitBtn);
    PP_RELEASE(browserPhotos);
    PP_RELEASE(scanBtn);
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
}

- (void)showMenu
{
    if (postView.text.length != 0 || hasPhoto ) {
        [self saveAndClearSheet];
        return;
    }
    [postView resignFirstResponder];
    [self.viewDeckController toggleLeftView];
}

- (void)saveAndClearSheet {    
    CMActionSheet *actionSheet = [[[CMActionSheet alloc] init]autorelease];
    [actionSheet addButtonWithTitle:@"保存" type:CMActionSheetButtonTypeFreedom block:^{
        [postView resignFirstResponder];
        hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hudLoading.opacity = PP_mbprogressHudOpacity;
        hudLoading.labelText = @"正在保存...";
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            sleep(0.1f);
            dispatch_async(dispatch_get_main_queue(), ^{
                hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
                hudLoading.labelText = @"已保存";
                hudLoading.delegate = self;
                hudLoading.mode = MBProgressHUDModeCustomView;
                [hudLoading hide:YES afterDelay:0.5];
            });
        });
    }];
    
    [actionSheet addSeparator];
    [actionSheet addButtonWithTitle:@"清空" type:CMActionSheetButtonTypeFreedom block:^{
        [postView resignFirstResponder];
        hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hudLoading.opacity = PP_mbprogressHudOpacity;
        hudLoading.labelText = @"正在清除...";
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            sleep(0.1f);
            dispatch_async(dispatch_get_main_queue(), ^{
                hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
                hudLoading.labelText = @"已清空";
                hudLoading.delegate = self;
                hudLoading.mode = MBProgressHUDModeCustomView;
                [hudLoading hide:YES afterDelay:0.5];
                postView.text = @"";
                postView.placeholder = NSLocalizedString(@"输入你要发布的内容...",);
                [self clearPreviewImage];
                [self deleteFile];
                hasPhoto = NO;
            });
        });
    }];
    [actionSheet addSeparator];
    [actionSheet addButtonWithTitle:@"继续" type:CMActionSheetButtonTypeFreedom block:^{
    }];
    [actionSheet present];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    return YES;
}

-(void)deleteFile {
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSString *uniquePath = [IMAGE_FILE_PATH stringByAppendingPathComponent:@"photo.jpg"];
    BOOL hasFile=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!hasFile) {
        Log(@"PostViewController <deleteFile>  no  file");
        return;
    }else {
        Log(@"PostViewController <deleteFile>  has  file");
        BOOL deleteFile= [fileManager removeItemAtPath:uniquePath error:nil];
        if (deleteFile) {
            Log(@"delete success");
        }else {
            Log(@"delete fail");
        }
    }
}

-(void)post:(id)sender {
    if( ![[UserManager sharedInstance] isLogin]){
        [self baseShowLoginSheet];
        return;
    }
    if( postView.text.length == 0 ){
        [self baseShowInfoHud:@"一点都不好笑，来点内容嘛！" andIsTop:YES];
        return;
    }
    if( postView.text.length < 10 ){
        [self baseShowInfoHud:@"内容太少了，冷不起来嘛！" andIsTop:YES];
        return;
    }
    if( postView.text.length > 2000 ){
        [self baseShowInfoHud:@"内容太长了，看完就真的冷冻了！" andIsTop:YES];
        return;
    }
    
    HAS_NO_NETWORK(self);
    [postView resignFirstResponder];
    
    hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hudLoading.labelText = @"正在发表...";
    hudLoading.opacity = PP_mbprogressHudOpacity;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *url = nil;
        if (!hasPhoto) {
            url = POST_NO_IMAGE;
        }else{
            url = POST_WITH_IMAGE;
        }
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
        request.userAgentString = @"lxh_app2_100";
        [request setAllowCompressedResponse:YES];
        [request addRequestHeader:@"Cookie" value:[NSString stringWithFormat:@"webpy_session_id=%@",[UserManager sharedInstance].sessionId] ];
        [request setPostFormat:ASIMultipartFormDataPostFormat];
        [request setDelegate:self];
        
        if (!hasPhoto) {
            [request setPostValue:@"image" forKey:@"type"];
            [request setPostValue:@"post_joke" forKey:@"action"];
            [request setPostValue:postView.text forKey:@"content"];
        }else{
            [request setPostValue:postView.text forKey:@"content"];
            [request setPostValue:@"image" forKey:@"type"];
            [request setPostValue:@"Joke" forKey:@"model_name"];
            [request setPostValue:nil forKey:@"title"];
            NSString *path = [IMAGE_FILE_PATH stringByAppendingPathComponent:@"photo.jpg"];
            Log(@"dispath path is:%@",path);
            [request setFile:path forKey:@"imagefile"];
        }
        
        [request setTimeOutSeconds:120];
        [request startSynchronous];
        NSError *error = [request error];
        NSString *res = @"";
        if(!error){
            NSString *tResponseStr = [request responseString];
            Log(@"res: %@",tResponseStr);
            SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
            id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
            [tJsonParser release], tJsonParser = nil;
            if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
                BOOL isSuccess = [[(NSDictionary *)tJsonObjects objectForKey:@"success"] boolValue];
                if (isSuccess) {
                    res = @"发布成功";
                    Log(@"success");
                    sleep(1);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
                        hudLoading.labelText = res;
                        hudLoading.mode = MBProgressHUDModeCustomView;
                        hudLoading.delegate = self;
                        [hudLoading hide:YES afterDelay:0.5];
                        
                        postView.text = @"";
                        postView.placeholder = NSLocalizedString(@"输入你要发布的内容...",);
                        [showCameraAndPohto setImage:nil forState:UIControlStateNormal];
                        [self deleteFile];
                        [self clearPreviewImage];
                    });
                    return;
                }else {
                    NSString *msg = [(NSDictionary *)tJsonObjects objectForKey:@"msg"];
                    NSString *error_info = [(NSDictionary *)tJsonObjects objectForKey:@"error_info"];
                    if([msg isEqualToString:@"exists"]){
                        res = error_info;
                    }else{
                        res = @"服务器错误，请稍后再试";
                        res = error_info;
                    }
                }
            }else{
                res = @"服务器错误，请稍后再试";
            }
        }else{
            Log ( @"%@",[error description]);
            res = @"网络异常,请稍后再试";
        }
        Log ( @"PostViewController <post> failed: %@",res);
        dispatch_async(dispatch_get_main_queue(), ^{
            hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Wrong.png"]] autorelease];
            hudLoading.labelText = res;
            hudLoading.mode = MBProgressHUDModeCustomView;
            [hudLoading hide:YES afterDelay:0.5];
        });
    });
}

#pragma --------alert操作----------
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    Log(@"tag %d buttonIndex:%d", alertView.tag, buttonIndex);
    if(alertView.tag == 0){
    } else if(alertView.tag == 1){
        [self back:nil];
    } else if(alertView.tag == 2){
        
    }
}

- (void)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)takeCamera:(id)sender{
    savePhotosAlbum = YES;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentModalViewController:imagePicker animated:YES];
    [imagePicker release];
}

- (IBAction)takePhoto:(id)sender{
    savePhotosAlbum = NO;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:imagePicker animated:YES];
    [imagePicker release];
}

- (void)addDeleteMark {
    float x = realImg.frame.origin.x -12 ;
    float y = realImg.frame.origin.y - 12 ;
    deleteMark = [[[UIButton alloc] initWithFrame:CGRectMake(x, y, 24.0, 24.0)] autorelease];
    [deleteMark setBackgroundImage:[UIImage imageNamed:@"post_delete_img.png"] forState:UIControlStateNormal];
    [deleteMark setBackgroundImage:[UIImage imageNamed:@"post_delete_img.png"] forState:UIControlStateHighlighted];
    [deleteMark addTarget:self action:@selector(clearPreviewImage) forControlEvents:UIControlEventTouchUpInside];
    [photoView addSubview:deleteMark];
    deleteMark.userInteractionEnabled = YES;
    scanBtn.hidden = NO;
}

- (void)clearPreviewImage {
    Log(@"clearPreviewImage start");
    [deleteMark setBackgroundImage:nil forState:UIControlStateNormal];
    if (previewImage.hidden == NO && realImg.hidden == NO) {
        previewImage.hidden = YES;
        realImg.hidden = YES;
        rabbitBtn.hidden = NO;
    }
    [self showCameraAndPohtoStatuOne];
    deleteMark.userInteractionEnabled = NO;
    scanBtn.hidden = YES;
}

- (void)showCameraAndPohtoStatuOne{
    [showCameraAndPohto setImage:[UIImage imageNamed:@"camera_1.png"] forState:UIControlStateNormal];
    [showCameraAndPohto setImage:[UIImage imageNamed:@"camera_2.png"] forState:UIControlStateHighlighted];
}

- (void)showCameraAndPohtoStatuTwo{
    [showCameraAndPohto setImage:[UIImage imageNamed:@"camera_2.png"] forState:UIControlStateNormal];
    [showCameraAndPohto setImage:[UIImage imageNamed:@"camera_1.png"] forState:UIControlStateHighlighted];
}


#pragma mark ---MWPhotoBrowser delegate---
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return browserPhotos.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < browserPhotos.count){
        return [browserPhotos objectAtIndex:index];
    }
    return nil;
}

#pragma mark ---MBProgressHUD delegate---
- (void)hudWasHidden:(MBProgressHUD *)hud
{
    [self.viewDeckController toggleLeftView];
}

#pragma mark ---IIViewDeckController delegate---
- (void)viewDeckController:(IIViewDeckController*)viewDeckController didChangeOffset:(CGFloat)offset orientation:(IIViewDeckOffsetOrientation)orientation panning:(BOOL)panning{
        [postView resignFirstResponder];
}
- (void)viewDeckController:(IIViewDeckController*)viewDeckController didShowCenterViewFromSide:(IIViewDeckSide)viewDeckSide animated:(BOOL)animated{
        [postView becomeFirstResponder];
}

//- (BOOL)viewDeckController:(IIViewDeckController*)viewDeckController shouldPan:(UIPanGestureRecognizer*)panGestureRecognizer{
//
//    Log(@"1");
//    [postView resignFirstResponder];
//    return YES;
//}
//
//- (void)viewDeckController:(IIViewDeckController*)viewDeckController applyShadow:(CALayer*)shadowLayer withBounds:(CGRect)rect{
//    Log(@"2");
//
//    [postView resignFirstResponder];
//}

- (IBAction)camera:(id)sender {
    hasPhoto = NO;
    [postView resignFirstResponder];
}
- (IBAction)scanPhotos:(id)sender {
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalPresentationFullScreen ;
    [self presentModalViewController:nc animated:YES];
    [nc release];
}

#pragma mark -
#pragma mark ---UIImagePickerController delegate---
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	[picker dismissModalViewControllerAnimated:YES];
    UIImage *uploadImage= [self scaleAndRotateImage:[info objectForKey:UIImagePickerControllerOriginalImage] andImageHeight:640];
    if (previewImage.hidden == YES && realImg.hidden == YES) {
        previewImage.hidden = NO;
        realImg.hidden = NO;
        rabbitBtn.hidden = YES;
        [self showCameraAndPohtoStatuTwo];
    }
    realImg.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self addDeleteMark];

    MWPhoto *mwphoto = [MWPhoto photoWithImage:realImg.image];
    [browserPhotos addObject:mwphoto];
    
    if (savePhotosAlbum) {
        UIImage *saveImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        UIImageWriteToSavedPhotosAlbum(saveImage, nil,nil, nil);
    }
    NSString *imgFilePath = [IMAGE_FILE_PATH stringByAppendingPathComponent:@"photo.jpg"];    
    NSData *imgData = UIImageJPEGRepresentation(uploadImage, 0.5);
    Log(@"%@",imgFilePath);
    if ( [imgData writeToFile:imgFilePath atomically:YES]) {
        Log(@"write success");
        hasPhoto = YES;
    }else{
        Log(@"write failed");
    }
    savePhotosAlbum = NO;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
	[picker dismissModalViewControllerAnimated:YES];
}

- (UIImage *)scaleAndRotateImage:(UIImage *)image andImageHeight:(int)scaleHeight{
    int kMaxResolution = scaleHeight; // 自定义高度，根据比例裁剪图片
    CGImageRef imgRef = image.CGImage;
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = roundf(bounds.size.width / ratio);
        }
        else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = roundf(bounds.size.height * ratio);
        }
    }
    
    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = image.imageOrientation;
    switch(orient) {
            
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
            
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
            
        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
            
        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
            
        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
            
        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
            
        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
            
        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
            
    }
    
    UIGraphicsBeginImageContext(bounds.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
    
    CGContextConcatCTM(context, transform);
    
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imageCopy;
}


- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

//背景色渐变函数（暂时没用到）
- (void)drawRect:(CGRect)rect
{
    UIColor* startColor = [UIColor redColor];
    UIColor* endColor = [UIColor blueColor];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextClipToRect(context, rect);
    [self drawGradientColor:context rect:rect point:CGPointMake(0, 0) point:CGPointMake(0, 100) options:(CGGradientDrawingOptions)NULL startColor:startColor endColor:endColor];
    CGContextRestoreGState(context);
}

- (void)drawGradientColor:(CGContextRef)context rect:(CGRect)clipRect point:(CGPoint) startPoint point:(CGPoint) endPoint options:(CGGradientDrawingOptions) options startColor:(UIColor*)startColor endColor:(UIColor*)endColor
{
    UIColor* colors [2] = {startColor,endColor};
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGFloat colorComponents[8];
    
    for (int i = 0; i < 2; i++) {
        UIColor *color = colors[i];
        CGColorRef temcolorRef = color.CGColor;
        
        const CGFloat *components = CGColorGetComponents(temcolorRef);
        for (int j = 0; j < 4; j++) {
            colorComponents[i * 4 + j] = components[j];
        }
    }
    CGGradientRef gradient =  CGGradientCreateWithColorComponents(rgb, colorComponents, NULL, 2);
    CGColorSpaceRelease(rgb);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, options);
    CGGradientRelease(gradient);
}

@end
